Page({
  data: {
    schema:[
    ],
    formData:{
    },
    title: '',
    result: '',
    remark: '',
    apiName: '',
    socket: null,
    connected: false,
    wifiInfo: null,
    errorMsg: '',
    message: '',
  },

  onLoad(options) {
    wx.setNavigationBarTitle({
      title: options.title,
    })
    
    this.setData({
      title: options.title,
      zh:options.zh,
      remark: options.remark,
      webUrl: options.webUrl
    })
  },
  createTCPSocket(e){
     // 创建TCP socket
     const socket = wx.createTCPSocket()
     console.log(socket)
    this.setData({
      result: socket,
      apiName: e.currentTarget.dataset.apiname
    })
  },

  // 输入服务器地址和端口
  inputHost: function(e) {
    this.setData({ host: e.detail.value })
  },
  inputPort: function(e) {
    this.setData({ port: e.detail.value })
  },
// 输入消息
onMessageInput(e) {
  this.setData({ message: e.detail.value })
},
  // 创建TCP连接
  connect: function(e) {
    if (!this.data.host || !this.data.port) {
      wx.showToast({ title: '请输入主机和端口', icon: 'none' })
      return
    }
    // 如果已有连接，先关闭
    if (this.data.socket) {
      this.data.socket.close()
    }
    // 创建TCP socket
    const socket = wx.createTCPSocket()
    this.setData({ socket: socket }) 
    // 连接服务器
    socket.connect({
      address: this.data.host,
      port: parseInt(this.data.port)
    })
   
    this.setData({
      result: socket,
      apiName: e.currentTarget.dataset.apiname
    })
  },
  bindWifi(e){
    // 如果已有连接，先关闭
    if (this.data.socket) {
      this.data.socket.close()
    }
    const tcp = wx.createTCPSocket()
    // 调用API获取Wi-Fi信息
    wx.getConnectedWifi({
      success: (result) => {
        console.log('Wi-Fi信息获取成功', result)
        console.log(wifiInfo)
        tcp.bindWifi({ BSSID: wifiInfo })
        this.setData({
          result: "成功",
          apiName: e.currentTarget.dataset.apiname
        })
      },
      fail: (err) => {
        console.error('Wi-Fi信息获取失败', err)
        // 错误码处理
        let errorMsg = '获取Wi-Fi信息失败'
        switch(err.errCode) {
          case 12001:
            errorMsg = '未连接到Wi-Fi'
            break
          case 12002:
            errorMsg = '系统不支持'
            break
          case 12003:
            errorMsg = '未授予Wi-Fi权限'
            break
        }
        this.setData({
          result: errorMsg,
          apiName: e.currentTarget.dataset.apiname
        })
      }
    })
    
    
  },
  onBindWifi(e){
    const tcp = wx.createTCPSocket()
    this.bindWifiWatch =  tcp.onBindWifi((res) => {
      this.setData({
        result: res,
        apiName: e.currentTarget.dataset.apiname
      })
    })
  },
  offBindWifi(e){
    const tcp = wx.createTCPSocket()
    tcp.offBindWifi(this.bindWifiWatch)
    this.setData({
      result: "已移除当一个 socket 绑定当前 wifi 网络成功时触发该事件的监听函数",
      apiName: e.currentTarget.dataset.apiname
    })
  },
  // 关闭连接
  close: function(e) {
    if (this.data.socket) {
      this.data.socket.close({
        success: () => {
          console.log('主动关闭连接')
          this.setData({
            result: '主动关闭连接',
            apiName: e.currentTarget.dataset.apiname
          })
        },
        fail: (err) => {
          console.log(`关闭连接失败: ${JSON.stringify(err)}`)
          this.setData({
            result: `关闭连接失败: ${JSON.stringify(err)}`,
            apiName: e.currentTarget.dataset.apiname
          })
        }
      })
    }else{
      this.setData({
        result: '当前没有TCP通信连接',
        apiName: e.currentTarget.dataset.apiname
      })
    }
  },
  onClose(e){
    // 关闭已有连接
    if (this.data.socket) {
      this.data.socket.close()
    }

    // 创建socket实例
    const socket = wx.createTCPSocket()
    this.setData({ socket })

    // 定义连接关闭事件的监听器
    this.closeListener = () => {
      this.setData({ socket: null })
      // 连接关闭后，移除所有监听器
      // this.cleanupSocket()
      this.setData({
        result: '监听到socket关闭事件',
        apiName: e.currentTarget.dataset.apiname
      })
    }
    // 注册连接关闭事件监听
    socket.onClose(this.closeListener)
  },
  offClose(e){
    if (this.closeListener) {
      this.data.socket.offClose(this.closeListener)
      this.closeListener = null // 清除引用
      this.setData({
        result: '已移除close事件监听器',
        apiName: e.currentTarget.dataset.apiname
      })
    }
  },
  onConnect(e){
    // 关闭已有连接
    if (this.data.socket) {
      this.data.socket.close()
    }
       // 创建socket实例
       const socket = wx.createTCPSocket()
       this.setData({ socket })
     // 定义连接事件的监听器
     this.connectListener = () => {
      this.setData({
        result: '监听到socket连接事件',
        apiName: e.currentTarget.dataset.apiname
      })
    }
    // 注册连接关闭事件监听
    socket.onConnect(this.connectListener)
  },
  offConnect(e){
    if (this.connectListener) {
      this.data.socket.offConnect(this.connectListener)
      this.connectListener = null // 清除引用
      this.setData({
        result: '已移除socket 连接成功事件监听器',
        apiName: e.currentTarget.dataset.apiname
      })
    }
  },
  onError(e){
    // 关闭已有连接
    if (this.data.socket) {
      this.data.socket.close()
    }
       // 创建socket实例
       const socket = wx.createTCPSocket()
       this.setData({ socket })
     // 定义错误事件监听器
     this.errorListener = (err) => {
      this.setData({
        result: `发生错误: ${JSON.stringify(err)}`,
        apiName: e.currentTarget.dataset.apiname
      })
    }
    // 注册错误事件监听
    this.data.socket.onError(this.errorListener)
  },
  offError(e){
    if (this.errorListener) {
      this.data.socket.offError(this.errorListener)
      this.errorListener = null // 清除引用
      this.setData({
        result: '已移除错误事件监听器',
        apiName: e.currentTarget.dataset.apiname
      })
    }
  },
  write(e){
    console.log(this.data.socket)
    if (this.data.socket==null) {
      wx.showToast({ title: '请先建立连接', icon: 'none' })
      return
    }
    const message = this.data.message.trim()
    if (!message) {
      wx.showToast({ title: '消息不能为空', icon: 'none' })
      return
    }
    try {
      // 将字符串编码为ArrayBuffer
      const encoder = new TextEncoder('utf-8')
      const data = encoder.encode(message)

      // 发送数据
      this.data.socket.write({
        data,
        success: () => {
          this.setData({
            result: '发送数据成功',
            apiName: e.currentTarget.dataset.apiname
          })
          // 清空输入框
          this.setData({ message: '' })
        },
        fail: (err) => {
          this.setData({
            result: `发送失败: ${err.errMsg}`,
            apiName: e.currentTarget.dataset.apiname
          })
          wx.showToast({ title: `发送失败: ${err.errMsg}`, icon: 'none' })
          console.error('发送消息失败:', err)
        }
      })
    } catch (e1) {
      this.setData({
        result: e1,
        apiName: e.currentTarget.dataset.apiname
      })
      wx.showToast({ title: '数据编码失败', icon: 'none' })
    }
  },
  onMessage(e){
    // 关闭可能存在的旧连接
    if (this.data.socket) {
      this.data.socket.close()
    }

    // 创建新的socket实例
    const socket = wx.createTCPSocket()
    this.setData({ socket })

    // 注册消息接收监听器
    this.messageListener = (res) => {
      try {
        // 接收的数据是ArrayBuffer格式，需要解码为字符串
        const decoder = new TextDecoder('utf-8')
        const receivedMsg = decoder.decode(res.data)
        
        this.setData({
          result: receivedMsg,
          apiName: e.currentTarget.dataset.apiname
        })
      } catch (e1) {
        this.setData({
          result: e1,
          apiName: e.currentTarget.dataset.apiname
        })
      }
    }
    socket.onMessage(this.messageListener)
  },
  offMessage(e){
    // 移除消息监听器
    if (this.messageListener) {
      this.data.socket.offMessage(this.messageListener)
      this.messageListener = null
      this.setData({
        result: '已移除消息监听器',
        apiName: e.currentTarget.dataset.apiname
      })
    }
  },
  // 页面卸载时确保关闭连接
  onUnload: function() {
    if (this.data.socket) {
      this.data.socket.close()
    }
  }
})